<template>
  <el-dialog
      :model-value="dialogVisible"
      title="修改阅读笔记"
      :width="dialogWidth"
      :before-close="handleClose"
      custom-class="update-note-dialog"
      @close="handleClose"
      :fullscreen="isMobile"
  >
    <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        :label-width="labelWidth"
        :label-position="labelPosition"
        class="note-form"
    >
      <el-form-item label="笔记标题" prop="title">
        <el-input
            v-model="form.title"
            placeholder="请输入笔记标题"
            :size="inputSize"
            clearable
        />
      </el-form-item>

      <el-form-item label="语雀链接" prop="yuqueUrl">
        <el-input
            v-model="form.yuqueUrl"
            placeholder="https://www.yuque.com/triumphxx/qdk5qn/..."
            :size="inputSize"
            clearable
        />
      </el-form-item>

      <el-form-item label="创建时间" prop="createdAt">
        <el-date-picker
            v-model="form.createdAt"
            type="datetime"
            placeholder="选择创建日期和时间"
            style="width: 100%"
            :size="inputSize"
            value-format="YYYY-MM-DDTHH:mm:ss"
            :default-value="new Date()"
        />
      </el-form-item>

      <el-form-item label="文件夹">
        <el-select
            v-model="form.folder"
            placeholder="请选择或输入文件夹"
            style="width: 100%"
            :size="inputSize"
            filterable
            allow-create
            clearable
            :reserve-keyword="false"
            class="folder-select"
        >
          <el-option
              v-for="folder in folderOptions"
              :key="folder.value"
              :label="folder.label"
              :value="folder.value"
          >
            <div class="folder-option">
              <el-icon v-if="folder.icon" class="folder-icon">
                <component :is="folder.icon" />
              </el-icon>
              <span class="folder-text">{{ folder.label }}</span>
            </div>
          </el-option>
        </el-select>
        <div class="folder-tips">
          可选择预设分类或输入自定义文件夹路径
        </div>
      </el-form-item>

      <el-form-item label="笔记内容">
        <el-input
            v-model="form.content"
            type="textarea"
            :rows="isMobile ? 3 : 4"
            placeholder="请输入笔记内容（可选）"
            resize="none"
            show-word-limit
            maxlength="1000"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer" :class="{ 'mobile-footer': isMobile }">
        <el-button
            @click="handleClose"
            :size="buttonSize"
            class="cancel-btn"
            :class="{ 'mobile-button': isMobile }"
        >
          取消
        </el-button>
        <el-button
            type="primary"
            @click="handleSubmit"
            :loading="submitLoading"
            :size="buttonSize"
            class="submit-btn"
            :class="{ 'mobile-button': isMobile }"
        >
          确认修改
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { ref, watch, nextTick, computed, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import { getNoteById, addNote } from '@/api/notes'
import {debounce} from "lodash";

export default {
  name: 'UpdateNoteDialog',
  props: {
    modelValue: {
      type: Boolean,
      required: true
    },
    noteId: {
      type: [String, Number],
      default: null
    }
  },
  emits: ['update:modelValue', 'success'],
  setup(props, { emit }) {
    const dialogVisible = ref(false)
    const formRef = ref()
    const submitLoading = ref(false)
    const isMobile = ref(false)

    // 响应式变量
    const screenWidth = ref(window.innerWidth)

    // 计算属性
    const dialogWidth = computed(() => {
      return isMobile.value ? '100%' : '500px'
    })

    const labelWidth = computed(() => {
      return isMobile.value ? '80px' : '100px'
    })

    const labelPosition = computed(() => {
      return isMobile.value ? 'top' : 'left'
    })

    const inputSize = computed(() => {
      return isMobile.value ? 'default' : 'large'
    })

    const buttonSize = computed(() => {
      return isMobile.value ? 'default' : 'large'
    })

    const form = ref({
      id: '',
      title: '',
      yuqueUrl: '',
      content: '',
      createdAt: dayjs().format('YYYY-MM-DDTHH:mm:ss'),
      folder: ''
    })

    // 预设文件夹选项
    const folderOptions = ref([
      { value: '个人成长', label: '个人成长' },
      { value: '孩子教育', label: '孩子教育' },
      { value: '投资理财', label: '投资理财' },
      { value: '创业经营', label: '创业经营' },
      { value: '家庭经营', label: '家庭经营' },
      { value: '经济社会', label: '经济社会' },
      { value: '人物传记', label: '人物传记' },
      { value: '身体管理', label: '身体管理' },
      { value: '历史哲学', label: '历史哲学' },
      { value: '科学启蒙', label: '科学启蒙' },
      { value: '其他', label: '其他' }
    ])

    const rules = {
      title: [
        { required: true, message: '请输入笔记标题', trigger: 'blur' },
        { min: 1, max: 100, message: '标题长度在 1 到 100 个字符', trigger: 'blur' }
      ],
      yuqueUrl: [
        { required: true, message: '请输入语雀链接', trigger: 'blur' },
        {
          pattern: /^https:\/\/www\.yuque\.com\/.+/,
          message: '请输入有效的语雀链接',
          trigger: 'blur'
        }
      ],
      createdAt: [
        { required: true, message: '请选择创建时间', trigger: 'change' }
      ]
    }

    // 检测屏幕宽度变化
    const checkScreenWidth = debounce(() => {
      screenWidth.value = window.innerWidth
      isMobile.value = screenWidth.value <= 768
    }, 100)

    // 加载笔记数据
    const loadNoteData = async (noteId) => {
      if (!noteId) return

      try {
        const response = await getNoteById(noteId)
        if (response.success && response.data) {
          const noteData = response.data
          form.value = {
            id: noteData.id,
            title: noteData.title || '',
            yuqueUrl: noteData.yuqueUrl || '',
            content: noteData.content || '',
            createdAt: noteData.createdAt ? dayjs(noteData.createdAt).format('YYYY-MM-DDTHH:mm:ss') : dayjs().format('YYYY-MM-DDTHH:mm:ss'),
            folder: noteData.folder || ''
          }
        } else {
          ElMessage.error('加载笔记数据失败')
        }
      } catch (error) {
        ElMessage.error('加载笔记数据失败: ' + (error.message || '未知错误'))
      }
    }

    // 监听外部 visible 变化
    watch(() => props.modelValue, (val) => {
      dialogVisible.value = val
      if (val && props.noteId) {
        loadNoteData(props.noteId)
      }
    })

    // 监听内部 visible 变化
    watch(dialogVisible, (val) => {
      emit('update:modelValue', val)
      if (!val) {
        resetForm()
      }
    })

    // 监听 noteId 变化
    watch(() => props.noteId, (newNoteId) => {
      if (dialogVisible.value && newNoteId) {
        loadNoteData(newNoteId)
      }
    })

    // 处理关闭
    const handleClose = () => {
      dialogVisible.value = false
    }

    // 重置表单
    const resetForm = () => {
      form.value = {
        id: '',
        title: '',
        yuqueUrl: '',
        content: '',
        createdAt: dayjs().format('YYYY-MM-DDTHH:mm:ss'),
        folder: ''
      }
      nextTick(() => {
        if (formRef.value) {
          formRef.value.clearValidate()
        }
      })
    }

    // 处理提交
    const handleSubmit = async () => {
      if (!formRef.value) return

      try {
        const valid = await formRef.value.validate()
        if (!valid) return

        submitLoading.value = true

        const response = await addNote( form.value)

        if (response.success) {
          ElMessage.success('笔记修改成功')
          emit('success')
          handleClose()
        }
      } catch (error) {
        if (error.errors) {
          return
        }
        ElMessage.error('修改笔记失败: ' + (error.message || '未知错误'))
      } finally {
        submitLoading.value = false
      }
    }

    // 生命周期
    onMounted(() => {
      checkScreenWidth()
      window.addEventListener('resize', checkScreenWidth)
    })

    onUnmounted(() => {
      window.removeEventListener('resize', checkScreenWidth)
    })

    return {
      dialogVisible,
      formRef,
      submitLoading,
      form,
      folderOptions,
      rules,
      isMobile,
      dialogWidth,
      labelWidth,
      labelPosition,
      inputSize,
      buttonSize,
      handleClose,
      handleSubmit
    }
  }
}
</script>

<style lang="scss" scoped>
.note-form {
  .el-form-item {
    margin-bottom: 20px;

    :deep(.el-form-item__label) {
      font-weight: 500;
      color: #303133;
    }
  }
}

.folder-select {
  :deep(.el-select__wrapper) {
    border-radius: 6px;
  }
}

.folder-option {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 0;
}

.folder-icon {
  color: #409eff;
  font-size: 16px;
}

.folder-text {
  font-size: 14px;
}

.folder-tips {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  line-height: 1.4;
}

.dialog-footer {
  display: flex;
  gap: 12px;
  justify-content: flex-end;

  &.mobile-footer {
    flex-direction: column;
    gap: 8px;
  }
}

.cancel-btn {
  min-width: 80px;

  &.mobile-button {
    width: 100%;
    min-width: auto;
    margin: 0;
  }
}

.submit-btn {
  min-width: 100px;

  &.mobile-button {
    width: 100%;
    min-width: auto;
    margin: 0;
  }
}

// 移动端样式优化
:deep(.update-note-dialog) {
  .el-dialog {
    border-radius: 8px;

    &__header {
      padding: 16px 20px;
      border-bottom: 1px solid #f0f0f0;

      .el-dialog__title {
        font-size: 16px;
        font-weight: 600;
      }
    }

    &__body {
      padding: 20px;
      max-height: calc(100vh - 200px);
      overflow-y: auto;
    }

    &__footer {
      padding: 16px 20px;
      border-top: 1px solid #f0f0f0;
    }
  }

  // 移动端全屏样式
  &.is-fullscreen {
    .el-dialog {
      width: 100%;
      height: 100%;
      margin: 0;
      border-radius: 0;

      &__body {
        max-height: calc(100vh - 120px);
      }
    }
  }
}

// 移动端表单优化
@media (max-width: 768px) {
  .note-form {
    .el-form-item {
      margin-bottom: 16px;

      :deep(.el-form-item__label) {
        font-size: 14px;
        margin-bottom: 6px;
        padding-bottom: 0;
      }
    }
  }

  .folder-tips {
    font-size: 11px;
    margin-top: 2px;
  }

  // 移动端输入框优化
  :deep(.el-input),
  :deep(.el-textarea),
  :deep(.el-date-editor) {
    .el-input__wrapper,
    .el-textarea__inner {
      border-radius: 6px;
    }
  }

  // 移动端选择器优化
  :deep(.el-select) {
    .el-select__wrapper {
      border-radius: 6px;
    }
  }

  // 移动端日期选择器优化
  :deep(.el-date-editor) {
    &.el-input {
      width: 100%;
    }
  }
}

// 超小屏幕优化
@media (max-width: 375px) {
  :deep(.update-note-dialog) {
    .el-dialog {
      &__body {
        padding: 16px;
      }

      &__footer {
        padding: 12px 16px;
      }
    }
  }

  .note-form {
    .el-form-item {
      margin-bottom: 14px;
    }
  }
}
</style>